package com.mengjing.adcommon.ad

import android.app.Activity
import android.util.Log
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd

class FullVideoAd(private var mActivity: Activity): BaseAd(mActivity) {
    private var mCount: Int = 0
    private var mTTAd: TTFullScreenVideoAd? = null

    /**
     * @param codeId 代码为ID
     * @param count 播放数量
     */
    fun showAd(codeId: String, count: Int) {
        mCodeId = codeId
        mCount = count

        loadAd()
    }

    private fun loadAd() {
        val adSlot = AdSlot.Builder()
                .setCodeId(mCodeId)
                .build()

        mTTAdNative.loadFullScreenVideoAd(adSlot, AdListener())
    }

    private inner class AdListener: TTAdNative.FullScreenVideoAdListener {
        override fun onError(code: Int, message: String?) {
            Log.d(TAG, "onError: load error: $code, $message")
        }

        override fun onFullScreenVideoAdLoad(ad: TTFullScreenVideoAd?) {
            mTTAd = ad
            mTTAd?.setFullScreenVideoAdInteractionListener(AdInteractionListener())
        }

        override fun onFullScreenVideoCached() {
            renderAd()
        }
    }

    private inner class AdInteractionListener: TTFullScreenVideoAd.FullScreenVideoAdInteractionListener {
        private var mIsShowedNextAd = false

        private fun showNextAd() {
            if (mIsShowedNextAd) return
            if (mCount <= 0) return

            showAd(mCodeId, mCount - 1);
        }

        override fun onAdShow() {
            Log.d(TAG, "onAdShow: ")
        }

        override fun onAdVideoBarClick() {
            Log.d(TAG, "onAdVideoBarClick: ")
        }

        override fun onAdClose() {
            Log.d(TAG, "onAdClose: ")
            showNextAd()
        }

        override fun onVideoComplete() {
            Log.d(TAG, "onVideoComplete: ")
            showNextAd()
        }

        override fun onSkippedVideo() {
            Log.d(TAG, "onSkippedVideo: ")
            showNextAd()
        }
    }

    private fun renderAd() {
        mTTAd?.showFullScreenVideoAd(mActivity)
        mTTAd = null
    }
}